import React, { useEffect, useState } from 'react';
import {
    notification,
    Spin,
    Modal,
    Form,
    Input,
    Upload,
    message,
    Radio,
    Select,
    Button,
    Table,
    InputNumber,
    Layout,
    Collapse
} from 'antd'
import { useSearchParams } from 'react-router-dom';
import { InboxOutlined } from '@ant-design/icons';
import { baseURL } from 'src/service/interceptors';

import {
    getCategory,
    addCategory,
    addFood
} from 'src/api/getData'

import './index.less'

const { Content } = Layout;
const { Option } = Select;
const { Panel } = Collapse;

function AddGoods() {
    const [searchParams, setSearchParams] = useSearchParams();
    console.log(searchParams, 'searchParams')
    const restaurant_id = 1; //todo:从query中取
    const [form] = Form.useForm();
    const [categorysForm] = Form.useForm();
    const [addaCategorysForm] = Form.useForm();
    const [addSpecsForm] = Form.useForm();

    const [fileList, setFileList] = useState([]); //图片上传
    const [loading, setLoading] = useState(false); //是否loading中
    const [visible, setVisible] = useState(false);//modal是否显示
    const [categorys, setCategorys] = useState([]); //分类
    const [specs, setSpecs] = useState([]);//规格列表
    const [foodSpecs, setFoodSpecs] = useState('one')

    useEffect(() => {
        getCategoryAsync(restaurant_id)
    }, [])


    async function getCategoryAsync() {
        try {
            const res = await getCategory(restaurant_id)
            setCategorys(res.data)

        } catch (error) {

        }
    }

    const normFile = (e) => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }

    // 添加商品
    async function handleOk() {
        try {
            const { category_id } = await categorysForm.validateFields();
            const { name, description, image_path, activity, attributes, packing_fee, price } = await form.validateFields();
            setLoading(true)
            const params = {
                name,
                description,
                image_path: image_path[0].response.data,
                activity,
                attributes,
                specs,
                category_id,
                restaurant_id
            }
            if (foodSpecs === 'one') {
                params.specs = [{
                    specs: '默认',
                    packing_fee,
                    price,
                }]
            }
            const res = await addFood(params);
            if (res.code === 0) {
                message.success('添加成功')
            }
        } catch (error) {
            console.error(error)
        }
        setLoading(false)
    }

    //删除规格
    function handleDelete(index) {
        const specsNew = [...specs]
        specsNew.splice(index, 1);
        setSpecs(specsNew)
    }

    // 添加分类
    async function handeAddCategory() {
        try {
            const values = await addaCategorysForm.validateFields();
            const res = await addCategory({
                ...values,
                restaurant_id
            });
            if (res.code === 0) {
                message.success('添加分类成功')
                getCategoryAsync(restaurant_id)
            }
        } catch (error) {

        }
    }

    return <Layout>
        <Content>


            <Spin
                spinning={false}
            >   <>
                    <h1>选择食品种类</h1>
                    <Form
                        form={categorysForm}
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                    >
                        <Form.Item
                            name='category_id'
                            label="食品种类"
                            rules={[{ required: true, message: '请输入!' }]}
                        >
                            <Select>
                                {
                                    categorys.map(item => {
                                        return <Option key={item.id} value={item.id}>{item.name}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                    </Form>

                    <Collapse>
                        <Panel header="添加食品种类" key="1">
                            <Form
                                form={addaCategorysForm}
                                labelCol={{ span: 4 }}
                                wrapperCol={{ span: 20 }}
                            >
                                <Form.Item
                                    name='name'
                                    label="食品种类"
                                    rules={[{ required: true, message: '请输入!' }]}
                                >
                                    <Input autoComplete="off" placeholder='请输入' />
                                </Form.Item>
                                <Form.Item
                                    name='description'
                                    label="种类描述"
                                    rules={[{ required: true, message: '请输入!' }]}
                                >
                                    <Input placeholder='请输入' />
                                </Form.Item>
                                <Form.Item noStyle>
                                    <Button onClick={handeAddCategory}>提交</Button>
                                </Form.Item>
                            </Form>
                        </Panel>
                    </Collapse>
                </>
            </Spin>

            <Spin spinning={loading}>
                <>
                    <h1>添加食品</h1>
                    <Form
                        form={form}
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                    >
                        <Form.Item
                            name='name'
                            label="食品名称"
                            rules={[{ required: true, message: '请输入!' }]}
                        >
                            <Input autoComplete="off" placeholder='请输入' />
                        </Form.Item>

                        <Form.Item
                            name='activity'
                            label="食品活动"
                            rules={[{ required: true, message: '请输入!' }]}
                        >
                            <Input autoComplete="off" placeholder='请输入' />
                        </Form.Item>
                        <Form.Item
                            name='description'
                            label="食品详情"
                            rules={[{ required: true, message: '请输入!' }]}
                        >
                            <Input autoComplete="off" placeholder='请输入' />
                        </Form.Item>

                        <Form.Item
                            label="上传食品图片"
                            name="image_path"
                            valuePropName="fileList"
                            getValueFromEvent={normFile}
                            rules={[{ required: true, message: '请上传食品图片!' }]}
                        >
                            <Upload.Dragger
                                name='file'
                                action={`${baseURL}v1/addimg/shop`}
                                size={2} //2M
                                accept="image/jpeg,image/png"
                                multiple={false}
                                listType="picture"
                                showUploadList={false}
                                onChange={(info) => {
                                    setFileList([info.file]);
                                    const status = info.file.status;
                                    info.fileList.forEach(item => {
                                        item.thumbUrl = '';
                                    });
                                    if (status === 'uploading') {
                                        console.log(info.file, info.fileList);

                                    }
                                    if (status === "removed") {

                                        setFileList([])
                                    }
                                    if (status === 'done') {
                                        console.log(`${info.file.name} file uploaded successfully.`);

                                    }
                                    if (status === 'error') {
                                        notification.error({
                                            message: "上传文件失败，请重试"
                                        });

                                    }
                                }}
                                beforeUpload={(file) => {
                                    return new Promise((resolve, reject) => {

                                        if (file.type !== 'image/jpeg') {
                                            notification.error({
                                                message: "导入格式不正确",
                                                duration: 5
                                            });
                                            return reject(false);
                                        }

                                        if (file.size / 1024 > 2 * 1024) {
                                            notification.error({
                                                message: "导入文件不能超过" + 2 + `M`,
                                                duration: 5
                                            });
                                            return reject(false);
                                        }

                                        return resolve(true);
                                    });
                                }}
                                fileList={fileList}
                            >
                                {
                                    fileList[0]?.response?.data ? <img src={`${baseURL}img/${fileList[0].response.data}`} /> :
                                        <>
                                            <p className="ant-upload-drag-icon">
                                                <InboxOutlined />
                                            </p>
                                            <p className="ant-upload-text">Click or drag file to this area to upload</p>
                                            <p className="ant-upload-hint">Support for a single or bulk upload.</p>
                                        </>
                                }
                            </Upload.Dragger>
                        </Form.Item>

                        <Form.Item
                            name='attributes'
                            label="食品特点"
                            rules={[{ required: true, message: '请输入!' }]}
                        >
                            <Select
                                mode="multiple"
                                allowClear
                            >
                                <Option value='新'>新品</Option>
                                <Option value='招牌'>招牌</Option>
                            </Select>
                        </Form.Item>

                        <Form.Item
                            name='foodSpecs'
                            label="食品规格"
                            rules={[{ required: true, message: '请输入!' }]}
                            initialValue={foodSpecs}
                        >
                            <Radio.Group onChange={(e) => {
                                setFoodSpecs(e.target.value)
                            }}>
                                <Radio value="one">单规格</Radio>
                                <Radio value="more">多规格</Radio>
                            </Radio.Group>
                        </Form.Item>
                        {
                            foodSpecs === 'one' ?
                                <>
                                    <Form.Item
                                        name='packing_fee'
                                        label="包装费"
                                        initialValue={5}
                                        rules={[{ required: true, message: '请输入!' }]}
                                    >
                                        <InputNumber placeholder='请输入' min={0} max={100} />
                                    </Form.Item>
                                    <Form.Item
                                        name='price'
                                        label="价格"
                                        initialValue={20}
                                        rules={[{ required: true, message: '请输入!' }]}
                                    >
                                        <InputNumber placeholder='请输入' min={0} max={10000} />
                                    </Form.Item>

                                </> : <Form.Item noStyle>
                                    <Form.Item noStyle>
                                        <Button type="primary"
                                            onClick={() => {
                                                setVisible(true)
                                            }}>添加规格</Button>
                                    </Form.Item>
                                    <Table
                                        columns={[
                                            {
                                                title: '规格',
                                                dataIndex: 'specs'
                                            },
                                            {
                                                title: '包装费',
                                                dataIndex: 'packing_fee'
                                            },
                                            {
                                                title: '价格',
                                                dataIndex: 'price'
                                            },
                                            {
                                                title: '操作',
                                                dataIndex: 'action',
                                                render(text, record, index) {
                                                    return <div>
                                                        <Button
                                                            onClick={() => handleDelete(index)}
                                                            type="primary"
                                                            danger
                                                        >删除</Button>
                                                    </div>
                                                }
                                            },
                                        ]}
                                        dataSource={specs}
                                        pagination={false}
                                    />
                                </Form.Item>
                        }
                        <Form.Item noStyle>
                            <Button type="primary" onClick={handleOk}>确认添加食品</Button>
                        </Form.Item>
                    </Form>
                </>

            </Spin>
        </Content>
        {
            visible && <Modal
                title="添加规格"
                visible
                onOk={async function () {
                    try {
                        const values = await addSpecsForm.validateFields();
                        setSpecs([...specs, values])
                        setVisible(false)
                    } catch (error) {

                    }
                }}
                onCancel={function () {
                    setVisible(false)
                }}
            >
                <Form
                    form={addSpecsForm}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name='specs'
                        label="规格"
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <Input autoComplete="off" placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        name='packing_fee'
                        label="包装费"
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <InputNumber placeholder='请输入' min={0} max={100} />
                    </Form.Item>
                    <Form.Item
                        name='price'
                        label="价格"
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <InputNumber placeholder='请输入' min={0} max={10000} />
                    </Form.Item>
                </Form>
            </Modal>
        }
    </Layout>
}

export default AddGoods